<template>
  <a-modal
    width="50vw"
    unmount-on-close
    :mask-closable="false"
    :visible="visible"
    title="查询"
    :footer="!loading && amount && isFirstPullDataSuccess"
    @cancel="handleCancel"
    @before-open="handleBeforeOpen"
    @before-ok="handleBeforeOk"
    @close="handleClose"
  >
    <div>
      <!-- 增加加载中，防止出现内容抖动 -->
      <a-spin tip="加载中..." v-if="loading" class="block" />
      <!-- 加载完成 -->
      <template v-else>
        <a-result
          class="p-5"
          v-if="!isFirstPullDataSuccess"
          status="warning"
          title="数据正在同步中，当列表中【最近数据更新时间】变更为当天，再操作查询即可"
        />
        <a-result class="p-5" v-else-if="!amount" status="error" title="账户余额不足，请先充值后查询违章" />
        <template v-else>
          <div v-if="options.btnType == 'login'" class="custom-text__success">登录成功！请选择查询的车辆</div>
          <a-radio-group v-model="radioSelected" :options="radioOptions" />
          <div v-if="radioSelected == 0">
            <fast-transfer style="width: 100%" v-model="form.carIdList" :selectedList="selectedList" :data-source="roleData" />
          </div>
          <div v-if="radioSelected == 1">
            <a-textarea v-model="form.licenseNo" placeholder="请输入车牌号, 以逗号(,)隔开" allow-clear />
          </div>
        </template>
      </template>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
  import { getViolationQueryCarCount, getAccountLastSyncDate, queryViolation, getViolationQueryBalance } from '@/api/asset/carViolation'
  import { Message } from '@arco-design/web-vue'

  import { computed, ref } from 'vue'

  const props = defineProps({
    visible: {
      type: Boolean,
      default: false,
    },
    options: {
      type: Object,
      default: () => ({}),
    },
  })
  const emits = defineEmits(['update:visible', 'onBeforeOk', 'close'])

  const visible = computed({
    get: () => props.visible,
    set: (val: boolean) => emits('update:visible', val),
  })

  const form = ref<any>({})
  const radioSelected = ref<number>(0)

  const radioOptions = [
    { label: '选择查询的车辆', value: 0 },
    { label: '输入车牌号', value: 1 },
  ]
  const selectedList = ref([])
  const roleData = ref([])

  const violationQueryCarList = (accountId?: string | number) => {
    getViolationQueryCarCount({ accountId, pageNumber: 1 }).then((res: any) => {
      roleData.value = res.result.data.map((item: any) => {
        return {
          label: item.licenseNo,
          value: item.carId,
        }
      })
    })
  }

  // 第三方首次拉取数据是否完成
  const isFirstPullDataSuccess = ref<boolean>(false)
  // 校验第三方首次拉取数据是否完成
  const checkFirstPullIsSuccess = async () => {
    // 2025-05-20 关闭校验
    return true
    // try {
    //   const res = await getAccountLastSyncDate({ accountId: id })
    //   const result = res.result
    //   // 存在 syncDate，说明历史上已经成功拉取过数据
    //   return !!result.syncDate || result.syncStatus == 2
    // } catch (err) {
    //   console.log('err', err)
    //   return false
    // }
  }

  // 校验余额
  const amount = ref<boolean>(false)
  const checkAccountAmount = async (id?: string | number) => {
    try {
      const res = await getViolationQueryBalance({ id })
      return res.result
    } catch (err) {
      console.log('err', err)
      return false
    }
  }

  // 显示 loading
  const loading = ref<boolean>(false)
  const handleBeforeOpen = async () => {
    // 开启 loading
    loading.value = true

    // 重置条件值
    amount.value = false
    isFirstPullDataSuccess.value = false

    console.log('props.options', props.options)

    form.value = {
      accountId: props.options?.id,
    }

    // 2025-05-20 关闭校验；同步中不能查询
    // 首先判断当前同步状态
    // if (props.options?.syncStatus != 1) {
    //   isFirstPullDataSuccess.value = false
    //   loading.value = false
    //   return
    // }

    // 条件1：第三方首次拉取数据已完成
    isFirstPullDataSuccess.value = await checkFirstPullIsSuccess(props.options?.id)
    if (isFirstPullDataSuccess.value) {
      // 条件2：余额充足
      amount.value = await checkAccountAmount(props.options?.id)
      if (amount.value) {
        violationQueryCarList(props.options?.id)
      }
    }

    // 结束 loading
    loading.value = false
  }

  const handleBeforeOk = async (done: (closed: boolean) => void) => {
    isFirstPullDataSuccess.value = await checkFirstPullIsSuccess(props.options?.id)
    if (!isFirstPullDataSuccess.value) {
      done(false)
      return
    }

    // 参数预处理
    const params = {
      ...form.value,
      carIdList: [],
      licenseNoList: [],
    }

    if (radioSelected.value == 0 && form.value.carIdList?.length) {
      params.carIdList = form.value.carIdList
    }

    if (radioSelected.value == 1 && form.value.licenseNo) {
      params.licenseNoList = form.value.licenseNo
        .replace(/[，\s\n\r]+/g, ',') // 处理中文逗号、空格、回车、换行
        .split(',')
        .filter(Boolean) // 过滤空值
    }

    // 参数校验
    if (radioSelected.value == 0 && !params.carIdList.length) {
      Message.warning('请选择要查询的车辆')
      done(false)
      return
    }

    if (radioSelected.value == 1 && !params.licenseNoList.length) {
      Message.warning('请输入要查询的车牌号')
      done(false)
      return
    }

    queryViolation(params)
      .then(() => {
        Message.success('查询成功')
        visible.value = false
        emits('onBeforeOk')
        done(true)
      })
      .catch((err: any) => {
        console.log('err', err)
        if (err == 'Error: 企业账号未登录，请先登录') {
          visible.value = false
        }

        done(false)
      })
  }

  const handleCancel = () => {
    visible.value = false
  }

  const handleClose = () => {
    form.value = {}
    roleData.value = []
    selectedList.value = []
    radioSelected.value = 0
    emits('close')
  }
</script>

<style scoped lang="less">
  .custom-text {
    font-weight: 500;
    font-size: 14px;
    color: #1d2129;

    &__success {
      color: #00b42a;
    }
    &__error {
      color: #ff5b5a;
    }
  }
</style>
